package br.com.srv.web.relatorio;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;

import br.com.srv.componentes.relatorio.controleextensao.service.ControleExtensaoService;
import br.com.srv.componentes.rota.service.RotaService;
import br.com.srv.model.ControleExtensaoTO;
import br.com.srv.model.RotaTO;
import br.com.srv.model.VeiculoTO;
import br.com.srv.security.SecurityPrincipal;
import br.com.srv.util.DateHelper;
import br.com.srv.web.BaseAction;

public class ControleExtensaoAction extends BaseAction {
	
	private final String PAGE_LISTA = "page_lista";

	public ActionForward preLoad(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		DynaValidatorForm frm = (DynaValidatorForm) form;
		frm.set("dataInicial", DateHelper.getTodayAsString());
		frm.set("dataFinal", DateHelper.getTodayAsString());
		frm.set("horaInicial", "00:00:00");
		frm.set("horaFinal", "23:59:59");
		
		carregarRotas(request);			
		
		return mapping.findForward(PAGE_LISTA);

	}

	private void carregarRotas(HttpServletRequest request) throws Exception {
		SecurityPrincipal principal = getPrincipal(request);		
		RotaTO rotaTO = new RotaTO();
		rotaTO.setClienteId(new Integer(principal.getClienteId()));		
		
		RotaService rotaService = (RotaService) getBeanSpring(RotaService.SERVICE_NAME);
		List<RotaTO> rotas = rotaService.buscarRotasAtivas(rotaTO);
		
		request.setAttribute("rotas", rotas);
	}
	
	public ActionForward consultar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ControleExtensaoTO controleExtensaoTO = getControleExtensaoTO(form, request);
		
		List<String> erros = validarControleExtensaoTO(controleExtensaoTO);
		//Caso ocorra algum erro de validacao, retorna para  pagina e exibe os erros. 
		if (!erros.isEmpty()) {
			saveActionErros(request, erros);
			request.setAttribute("controleExtensao", controleExtensaoTO);
			
			carregarRotas(request);
			request.setAttribute("rotaId", controleExtensaoTO.getRotaId());
			
			return mapping.findForward(PAGE_LISTA);
		}
		
		ControleExtensaoService controleExtensaoService = (ControleExtensaoService)getBeanSpring(
				ControleExtensaoService.SERVICE_NAME);
		List<Map> resultado = controleExtensaoService.consultaControleExtensao(controleExtensaoTO);
		
		request.setAttribute("resultado", resultado);
		
//		carregarRotas(request);
//		request.setAttribute("rotaId", controleExtensaoTO.getRotaId());
		
		return carregarVeiculos(mapping, form, request, response);

	}
	
	@SuppressWarnings("unchecked")
	public ActionForward carregarVeiculos(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		DynaValidatorForm frm = (DynaValidatorForm) form;	
		@SuppressWarnings("unused")
		Map<String, Object> params = frm.getMap();
		ControleExtensaoTO controleExtensao = getControleExtensaoTO(form, request);

		List<VeiculoTO> veiculos = new ArrayList<VeiculoTO>();		

		
		//se o ID da cerca for null n�o deve retornoar veiculos.
		if (controleExtensao.getRotaId() != null && !controleExtensao.getRotaId().equals("")) {
			RotaService rotaService = (RotaService)getBeanSpring(RotaService.SERVICE_NAME);
			veiculos = rotaService.buscarVeiculosDaRota(new Integer(controleExtensao.getRotaId()));
		}
		
		//casrrega as rotas ativas do cliente no request.
		carregarRotas(request);
		request.setAttribute("veiculos", veiculos);
		request.setAttribute("rotaId", controleExtensao.getRotaId());
		
		return mapping.findForward(PAGE_LISTA);		
	}	
	
	/**
	 * Passa os dados do form e constr�i um VeiculoTO.
	 * return ClienteTO.
	 */
	@SuppressWarnings("unchecked")
	private ControleExtensaoTO getControleExtensaoTO(ActionForm form, HttpServletRequest request) {
		DynaValidatorForm frm = (DynaValidatorForm) form;	
		Map<String, Object> params = frm.getMap();
		
		ControleExtensaoTO controleExtensao = new ControleExtensaoTO();
		
		controleExtensao.setRotaId((String)params.get("rotaId"));
		controleExtensao.setVeiculoId((String)params.get("veiculoId"));
		controleExtensao.getPeriodoTO().setDataInicial((String)params.get("dataInicial"));
		controleExtensao.getPeriodoTO().setDataFinal((String)params.get("dataFinal"));
		controleExtensao.getPeriodoTO().setHoraInicial((String)params.get("horaInicial"));
		controleExtensao.getPeriodoTO().setHoraFinal((String)params.get("horaFinal"));
		
		controleExtensao.setClienteId(getPrincipal(request).getClienteIdBD());
		
		try {
			new Integer(controleExtensao.getVeiculoId());
		} catch (Exception e) {
			controleExtensao.setVeiculoId("");
		}
		
		return controleExtensao;
	}
	
	/**
	 * Executa valida��o do VelocidadeMediaTO antes de fazer a consulta. 
	 * @param velocidadeMediaTO VelocidadeMediaTO
	 * @return Lista de erros.
	 */
	private List<String> validarControleExtensaoTO(ControleExtensaoTO controleExtensaoTO) {
		
		List<String> erros = new ArrayList<String>();
		
		String dataInicial = controleExtensaoTO.getPeriodoTO().getDataInicial();
		String dataFinal = controleExtensaoTO.getPeriodoTO().getDataFinal();
		String horaInicial = controleExtensaoTO.getPeriodoTO().getHoraInicial();
		String horaFinal = controleExtensaoTO.getPeriodoTO().getHoraFinal();		
		
		if (dataInicial == null || dataInicial.equals("")) {
			erros.add("Data Inicial � um campo obrigat�rio.");
		}
		
		if (dataFinal == null || dataFinal.equals("")) {
			erros.add("Data Final � um campo obrigat�rio.");
		}	
		
		if (horaInicial == null || horaInicial.equals("")) {
			erros.add("Hora Inicial � um campo obrigat�rio.");
		}
		
		if (horaFinal == null || horaFinal.equals("")) {
			erros.add("Hora Final � um campo obrigat�rio.");
		}			
		
		return erros;
	}
	
}
